<template>
  <div>
    <el-form class="base_form" :model="submitForm" :rules="rules" ref="ruleForm" label-width="200px">
      <el-form-item label="商品品类" prop="category_id">
        <el-select v-model="submitForm.category_id" placeholder="请选择商品品类" @change="categoryChange">
          <el-option v-for="item in categoryList" :key="item.category_id" :label="item.name" :value="item.category_id">
          </el-option>
        </el-select>
        <p class="color-999 inline-block" style="margin-left:15px">未申请商品品类？点击立即<el-button v-if="$hasMethod('#apply')"
            type="text" @click="$router.push({ name: 'goodsCategoryApply' })">申请品类</el-button>
        </p>
      </el-form-item>
      <el-form-item label="商品名称" prop="goods_name">
        <el-input v-model="submitForm.goods_name" style="width:100%" maxlength="50" show-word-limit
          placeholder="请输入商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品推广名称" prop="extension_title">
        <el-input v-model="submitForm.extension_title" style="width:100%" maxlength="50" show-word-limit
          placeholder="请输入推广商品推广名称"></el-input>
      </el-form-item>
      <el-form-item label="推广关键字">
        <el-input v-model="submitForm.spread_title" style="width:100%" maxlength="50" show-word-limit
          placeholder="请输入推广关键字，以中文逗号隔开"></el-input>
      </el-form-item>
      <el-form-item label="新旧" prop="new_grade">
        <el-radio-group v-model="submitForm.new_grade">
          <el-radio v-for="(val, key) in initData.new_grade" :key="key" :label="key">{{ val }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="租赁标签">
        <div v-for="item in initData.rent_label" :key="item" class="inline-block pointer rent_tag"
          :class="{ 'active': isTagCheck(item) }" @click="handleTagClick(item)">
          <span class="inline-block color-666">{{ item }}</span>
          <span class="inline-block text-center"><i v-if="isTagCheck(item)"
              class="el-icon-check blue-font vertical-middle check_icon"></i></span>
        </div>
      </el-form-item>
      <el-form-item label="商品封面" prop="imgurl">
        <crop-upload 
          ref="coverUpload"
          show-type="photo"
          :fixScale="true"
          :is-square="true"
          :always-crop="true"
          :fixedBox="false"
          :init-val="submitForm.imgurl"
          wrapper-width="120px"
          wrapper-height="120px"
          :photo-width="120"
          :photo-height="120"
          :autoCropWidth="150"
          :autoCropHeight="150"
          cropperWidth="400px"
          cropperHeight="400px"
          dialogWidth="600px"
          :min-width="150"
          :min-height="150"
          :enlarge="5"
          :params="1"
          @setVal="setUrl">
          </crop-upload>
        <div class="color-999">注：尺寸为150*150px及以上正方形，图片要求为纯白色底图
          <el-popover placement="right" width="400" trigger="hover">
            <div class="img_exp">
              <h5>商品封面图片示例</h5>
              <div class="exp_wrap">
                <p class="item">
                  <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp1.png')"></el-image>
                  <span><i class="green-font el-icon-success"></i>推荐</span>
                </p>
                <p class="item">
                  <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp2.png')"></el-image>
                  <span><i class="red-font el-icon-error"></i>不推荐</span>
                </p>
                <p class="item">
                  <el-image style="width: 100px; height: 100px" :src="require('@/assets/images/exp3.png')"></el-image>
                  <span><i class="red-font el-icon-error"></i>不推荐</span>
                </p>
              </div>
              <p class="red-font">注：图片要求150*150像素以上的正方形图片；<br />注：上传封面图片要求纯白色底图；<br />注：精品纯白色底图可上首页推荐位！</p>
            </div>
            <el-button type="text" slot="reference">图片示例></el-button>
          </el-popover>
        </div>
      </el-form-item>
      <el-form-item label="商品图片" prop="carousel_img">
        <crop-upload
          ref="cropUpload"
          :sort="true"
          :multiple="true"
          :always-crop="true"
          show-type="photo"
          :fixScale="true"
          :fixedBox="false"
          :is-square="true"
          :init-val="submitForm.carousel_img"
          wrapper-width="400px"
          wrapper-height="400px"
          :autoCropWidth="150"
          :autoCropHeight="150"
          cropperWidth="400px"
          cropperHeight="400px"
          dialogWidth="600px"
          :enlarge="5"
          :maxNum="8"
          :photo-width="400"
          :photo-height="400"
          :min-width="400"
          :min-height="400"
          :params="1"
          @setVal="bannerChange"
        ></crop-upload>
        
        
      </el-form-item>
      <el-form-item label="商品详情">
        <div class="editor_wrap">
          <text-editor v-model="submitForm.goods_content" />
        </div>
      </el-form-item>
      <el-form-item label="商品销量" prop="refuse">
        <el-input v-model="submitForm.refuse" show-word-limit placeholder="请输入商品销量"></el-input>
      </el-form-item>
      <el-form-item label="租赁说明" prop="leaseInfoImg ">
        <el-select v-model="submitForm.leaseInfoImg" placeholder="请选择" @change="changeImg($event)">
          <el-option v-for="(item, index) in leaseInfoSelect" :key="index" :label="item.name" :value="item.value" />
        </el-select>
        <!-- <p class="tip"><img src="" alt="" ref="leaseImg"></p> -->
      </el-form-item>
      <el-form-item label="租赁方式" prop="pact_type">
        <el-checkbox-group v-model="submitForm.pact_type">
          <el-checkbox v-for="(val, key) in initData.pact_type" :key="key" :value="val" :label="key" :disabled="isShow" @change="change_pact_type($event,key)">{{ val }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="起租日设置">
        <el-select v-model="submitForm.startDate" placeholder="请选择" @change="changeStartDate($event)">
          <el-option v-for="(item, index) in startDateSelect" :key="index" :label="item + '天'" :value="item" />
        </el-select>
        <p class="tip">起租日为租赁合同起租时间，默认起租日为下单日3天后。</p>
      </el-form-item>
      <el-form-item label="服务城市" prop="province">
        <el-cascader v-model="submitForm.province" filterable placeholder="请选择" :options="areaList" :props="optionProps" separator="-" />
      </el-form-item>
      <el-form-item label="租赁地址">
        <el-select v-model="submitForm.service_address" placeholder="请选择">
          <el-option v-for="(item, index) in initData.shop_address" :key="index" :label="item.address" :value="item.address" />
        </el-select>
        <p class="color-999 inline-block" style="margin-left:15px">没有租赁地址？点击添加
          <el-button type="text" @click="goToRentAd">租赁地址</el-button>
        </p>
      </el-form-item>
      <el-form-item label="配送方式" prop="send_out" style="margin-bottom:0px">
        <div class="flex align-center">
          <label class="text-right" style="width:40px;margin-right:20px"><span class="required-icon">*</span>寄出</label>
          <el-radio-group v-model="submitForm.send_out">
            <el-radio v-for="(val, key) in initData.send_out" :key="key" :label="key">{{ val }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="flex align-center">
          <label class="text-right" style="width:40px;margin-right:20px">归还</label>
          <el-radio-group v-model="submitForm.return">
            <el-radio v-for="(val, key) in initData.return" :key="key" :label="key">{{ val }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
    </el-form>
    <div class="fix-footer-btns">
      <!-- <div class="flex justify-center align-center">
        <label style="margin-right:20px"><i class="required-icon" style="margin-right:5px">*</i>商品审核后状态:</label>
        <el-radio v-model="status" :label="1">商品上架</el-radio>
        <el-radio v-model="status" :label="2">商品下架</el-radio>
      </div> -->
      <!-- <el-divider /> -->
      <div>
        <template v-if="!draftId">
          <el-button v-if="$hasMethod('#saveBaseDraft')" size="small" @click="saveToDraft">保存草稿</el-button>
          <el-button v-if="$hasMethod('#addBase')" size="small" type="primary" @click="nextStep">下一步</el-button>
        </template>
        <template v-else>
          <el-button size="small" @click="$router.go(-1)">返回</el-button>
          <el-button size="small" type="primary" @click="save">保存</el-button>
          <el-button v-if="$hasMethod('#submit') && !hideAuditBtn" size="small" type="warning" @click="submitAudit">提交审核
          </el-button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import cropUpload from '@/components/cropUpload'
import textEditor from '@/components/wangEditor'
import { getAreas } from '@/api/index'
import { getShopCategory, getGoodsRentData, getGoodsParameter, addGoodsData, editGoodsData, getGoodsAndSetmeal, goodsSubmitReview, getParameterList } from '@/api/goods'
import { Form } from 'element-ui'
export default {
  components: { cropUpload, textEditor },
  props: ['editId', 'activeTab', 'draftId'],
  data() {
    return {
      submitForm: {
        category_id: null,
        goods_name: '',
        spread_title: '',
        new_grade: '100',
        rent_label: [],
        imgurl: '',
        carousel_img: [],
        goods_content: '',
        pact_type: [], // 租赁方式已选数据
        province: [],
        service_address: '',
        send_out: '1',
        return: '1',
        startDateSelect: [], // 起租日
        leaseInfoSelect: [], // 租赁说明
        transfer_cost: '',
        leaseInfoImg: [],
        refuse: '', // 商品销量
        startDate: [],
		extension_title: '' // 商品推广名称
      },
      rules: {
        carousel_img: [
          { required: true, message: '请上传商品图片', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择服务城市', trigger: 'change' }
        ],
        category_id: [
          { required: true, message: '请选择商品品类', trigger: 'change' }
        ],
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        extension_title: [
          { required: true, message: '请输入商品推广名称', trigger: 'blur' }
        ],
        imgurl: [
          { required: true, message: '请上传商品封面', trigger: 'change' }
        ],
        new_grade: [
          { required: true, message: '请选择新旧程度', trigger: 'change' }
        ],
        leaseInfoImg: [
          { required: true, message: '请选择租赁说明', trigger: 'change' }
        ]
      },
      areaList: [], // 服务城市
      adsList: [], // 租赁地址
      categoryList: [], // 品类列表
      optionProps: {
        value: 'id',
        label: 'name',
        expandTrigger: 'hover',
        children: 'sub'
      },
      initData: {
        new_grade: {}, // 新旧程度
        rent_label: [], // 标签
        pact_type: [], // 租赁方式
        send_out: {}, // 寄出
        return: {}, // 归还
        shop_address: [] // 租赁地址
      },
      goodsParams: [], // 商品参数
      status: 2, // 商品审核后上架/下架
      hideAuditBtn: false,
      pact_type: [] // 多选租赁方式
    }
  },
  mounted() {
    this.init()
    this.getData()
   
  },
  beforeDestroy() {
    if (!this.editId) {
      sessionStorage.setItem('baseInfo', JSON.stringify({ formData: this.submitForm, goodsParams: this.goodsParams }))
      sessionStorage.setItem('goodsStatus', this.status)
    }
  },
  methods: {
    // 租赁说明
    changeImg(value) {
      // const that = this;s
      // that.$refs['leaseImg'].style.width = "300px";
      // that.$refs['leaseImg'].setAttribute('src',this.$globalObj.imgBaseUrl + value);
    },
    change_pact_type(e, value) {
      const pactList = this.submitForm['pact_type']
      if (e === true) {
        pactList.push(value)
      } else {
        pactList.splice(this.pact_type.indexOf(value), 1)
      }
      pactList.forEach((item, index) => {
        if (item === null) {
          pactList.splice(index, 1)
        }
      })
      const arr = Array.from(new Set(pactList))
      arr.forEach((item, index) => {
        if (item === undefined) {
          this.pact_type.splice(item, index)
        }
      })
      this.pact_type = arr
      sessionStorage.setItem('baseOfPactType', Array.from(new Set(pactList)))
      // this.$set(this.submitForm.pact_type,this.pact_type)
    },
    goToRentAd() {
      this.$confirm('跳转前请先保存草稿，确认继续跳转吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.$router.push({ name: 'shopRentAd' })
      }).catch(() => { })
    },
    // 提交审核
    submitAudit() {
      goodsSubmitReview(this.editId).then(res => {
        this.$router.push({ name: 'goodsSuccess', params: { goodsId: this.editId, isEdit: true }})
      })
    },
    // 保存草稿
    saveToDraft() {
      if (!this.submitForm.category_id || !this.submitForm.goods_name || !this.submitForm.extension_title) {
        this.$message({
          message: '商品品类和商品名称不能为空',
          type: 'warning'
        })
        return
      }
      const data = { ...this.submitForm, status: this.status, operation_type: 1 }
      data.rent_label = data.rent_label.join(',')
      data.province_id = data.province && data.province[0] ? data.province[0] : ''
      data.show_ity = data.province && data.province[1] ? data.province[1] : ''
      data.carousel_img = data.carousel_img.join(',')
      data.custom = this.goodsParams.map(item => { return { 'field_title': item.field_title, 'field_val': item.field_type !== 3 ? item.field_val : item.field_val.join(',') } })
      delete data.province
      if (!sessionStorage.getItem('goodsId')) {
        // 没有商品id，新增
        addGoodsData(data).then(res => {
          sessionStorage.setItem('goodsId', res.goods_id)
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        })
      } else {
        // 有商品id，编辑
        data.goods_id = sessionStorage.getItem('goodsId')
        editGoodsData(data).then(res => {
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        })
      }
    },
    // 获取品类对应的商品参数
    async categoryChange(val) {
      if (!val) {
        return
      }
      await getGoodsParameter(val).then(res => {
        this.goodsParams = []
        for (const item of res) {
          item.field_val = ''
          item.field_list = item.field_list.split(',')
          this.goodsParams.push({ ...item })
        }
      })
    },
    save() {
      const that = this
      this.$confirm('商品信息变更需要平台审核，审核时间1个工作日，确定修改商品？', '修改商品', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        that.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            // 检查商品参数必填项
            for (const item of that.goodsParams) {
              if (item.must_is && (!item.field_val || item.field_val.length === 0)) {
                that.$message({
                  message: '商品参数' + item.field_title + '必填',
                  type: 'warning'
                })
                return
              }
            }
            const data = { goods_id: that.draftId, ...that.submitForm, status: that.status, operation_type: 3 }
            data.rent_label = data.rent_label.join(',')
            data.province_id = data.province[0]
            data.show_ity = data.province[1]
            data.carousel_img = data.carousel_img.join(',')
            data.custom = that.goodsParams.map(item => { return { 'field_title': item.field_title, 'field_val': item.field_type !== 3 ? item.field_val : item.field_val.join(',') } })
            delete data.province
            editGoodsData(data).then(res => {
              that.$message({
                message: '保存成功',
                type: 'success'
              })
              that.$router.push({ name: 'goodsSuccess', params: { goodsId: that.draftId, isEdit: true }})
            })
          } else {
            that.$message({
              message: '请检查表单错误',
              type: 'error'
            })
            return false
          }
        })
      }).catch(() => { })
    },
    nextStep() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.pact_type = this.submitForm['pact_type']
          // 检查商品参数必填项
          for (const item in this.goodsParams) {
            if (item.must_is && !item.field_val) {
              this.$message({
                message: '商品参数' + item.field_title + '必填',
                type: 'warning'
              })
              return
            }
          }
          const data = { ...this.submitForm, status: this.status, operation_type: 3, pact_type: Array.from(new Set(this.pact_type)).sort() }
          data.rent_label = data.rent_label.join(',')
          data.province_id = data.province[0]
          data.show_ity = data.province[1]
          data.carousel_img = data.carousel_img.join(',')
          data.custom = this.goodsParams.map(item => { return { 'field_title': item.field_title, 'field_val': item.field_type !== 3 ? item.field_val : item.field_val.join(',') } })
          delete data.province
		  if (!sessionStorage.getItem('goodsId')) {
			  // console.log(data);
			  // 没有商品id，新增
			  addGoodsData(data).then(res => {
				sessionStorage.setItem('goodsId', res.goods_id)
				this.$emit('changeTab')
			  })
			} else {
			  // 有商品id，编辑
			  data.goods_id = sessionStorage.getItem('goodsId')
			  editGoodsData(data).then(res => {
				this.$emit('changeTab')
			  })
			}
        } else {
          this.$message({
            message: '请检查表单错误',
            type: 'error'
          })
          return false
        }
      })
    },
    changeNumberInput(key, value) {
      const pattern = /^[1-9][0-9]*$/ // 正整数的正则表达式
      // 不符合正整数时
      if (!pattern.test(value)) {
        // input 框绑定的内容为空
        this.submitForm[key] = ''
      }
    },
    bannerChange(val, type) {
      if (type === 'sort') {
        this.submitForm.carousel_img = val[0]
        return
      }
      if (type === 'del') {
        this.submitForm.carousel_img.splice(val[0], 1)
      } else {
        this.submitForm.carousel_img.push(val[0])
      }
      // this.$refs.cropUpload.sortList = this.submitForm.carousel_img
    },
    setUrl(val) {
      this.submitForm.imgurl = val[0]
    },
    handleTagClick(tag) {
      const index = this.submitForm.rent_label.findIndex(item => item === tag)
      if (index > -1) {
        this.submitForm.rent_label.splice(index, 1)
      } else {
        this.submitForm.rent_label.push(tag)
      }
    },
    // 判断标签是否选中
    isTagCheck(tag) {
      return this.submitForm.rent_label.findIndex(item => item === tag) > -1
    },
    init() {
      getShopCategory().then(res => {
        this.categoryList = res || []
      })
      getAreas().then(res => {
        this.areaList = res ? res[0].sub : []
        this.submitForm.province = [7459]
      })
      getGoodsRentData().then(res => {
        if (res) {
          this.initData = res
        }
        this.submitForm.service_address = this.initData.shop_address[0].address
      })
      getParameterList().then(res => {
        this.startDateSelect = res.start_date || []
        this.leaseInfoSelect = res.lease_info || []
        this.submitForm.leaseInfoImg = this.leaseInfoSelect[0].value
        this.submitForm.startDate = this.startDateSelect[3]
      })
    },
    getData() {
      this.isShow = false
      // 编辑操作
      if (this.draftId) {
        getGoodsAndSetmeal(this.draftId).then(async res => {
          sessionStorage.setItem('goodsId', res.id)
          for (const key in this.submitForm) {
            if (key === 'carousel_img') {
              this.submitForm[key] = res.carousel_images ? res.carousel_images.split(',') : []
            } else if (key === 'goods_name') {
              this.submitForm[key] = res.title
            } else if (key === 'extension_title') {
              this.submitForm[key] = res.extension_title
            } else if (key === 'province') {
              this.submitForm[key] = res.province_id && res.show_ity ? [res.province_id, res.show_ity] : [res.province_id]
            } else if (key === 'rent_label') {
              this.submitForm[key] = res.rent_label ? res.rent_label.split(',') : []
            } else if (key === 'pact_type') {
              this.submitForm[key] = res.pact_type
              sessionStorage.setItem('editPact', res.pact_type)
              this.isShow = true
            } else if (key === 'return') {
              this.submitForm[key] = res.convey_type2 + ''
            } else if (key === 'send_out') {
              this.submitForm[key] = res.convey_type1 + ''
            } else if (res[key]) {
              this.submitForm[key] = res[key]
            } else if (key === 'leaseInfoImg') {
              this.submitForm[key] = res.lease_info
            } else if (key === 'startDate') {
              const arr = []
              arr.push(res.start_date)
              this.submitForm[key] = arr
            }
          }
          this.status = res.status || 2
          await this.categoryChange(res.category_id)
          for (const item of res.attribute) {
            for (const param of this.goodsParams) {
              if (item.field_title === param.field_title) {
                param.field_val = param.field_type === 3 ? item.field_val.split(',') : item.field_val
              }
            }
          }
          this.setMealList(res.setmeal)
        })
      } else {
        // 新增
        if (sessionStorage.getItem('baseInfo')) {
          const data = JSON.parse(sessionStorage.getItem('baseInfo'))
          this.submitForm = { ...data.formData }
          this.goodsParams = [...data.goodsParams]
        }
        this.status = parseInt(sessionStorage.getItem('goodsStatus')) || 2
      }
    },
    setMealList(mealList) {
      const list = mealList.map(item => {
        const formData = {
          setmeal_id: '',
          title: '',
          lease_set: 1,
          is_huabei: 2,
          huabei_data: [
            {
              lease_term: '',
              rent_total: '',
              three_bear: '',
              three_fee: '',
              six_bear: '',
              six_fee: '',
              twelve_bear: '',
              twelve_fee: ''
            }
          ],
          quantity: '',
          foregift: '',
          is_buy_out: 1,
          price: '',
          start_date: ''
        }
        let monthList = [
          {
            lease_time: null,
            lease_price: ''
          }
        ]
        let dayList = [
          {
            lease_time: '',
            lease_price: ''
          }
        ]
        let customList = []
        for (const key in formData) {
          if (key === 'huabei_data') {
            if (item.is_huabei === 1) {
              formData[key] = item[key]
            }
          } else if (key === 'setmeal_id') {
            formData[key] = item.id
          } else {
            formData[key] = item[key]
          }
        }
        if (item.lease_set === 1) {
          monthList = item.spec
        } else if (item.lease_set === 2) {
          dayList = item.spec
        } else {
          customList = item.spec
        }
        return { formData, monthList, dayList, customList }
      })
      sessionStorage.setItem('mealInfo', JSON.stringify(list))
      this.$parent.mealTabs = JSON.parse(sessionStorage.getItem('mealInfo')).length
    }
  }
  // created(){
  //    this.init();
  //   this.getData();
  // },
}
</script>

<style lang="scss" scoped>
.editor_wrap {
  width: 700px;

  /deep/.text {
    height: 360px;
    overflow: auto;
  }
}

.base_form {
  padding: 30px 120px 30px 0;
}

.params_wrap {
  width: 100%;
  padding: 20px;
  background-color: $gray-content;

  label {
    display: inline-block;
    width: 120px;
    text-align: right;
    margin-right: 10px;
  }

  &>div {
    margin-bottom: 10px;
  }
}

.type_tip {
  color: #999999;
  line-height: 22px;

  span {
    color: #ff4146;
  }
}

.rent_tag {
  height: 30px;
  line-height: 28px;
  border: 1px solid #eeeeee;
  border-radius: 3px;

  span:first-child {
    padding-left: 5px;
    padding-right: 5px;
    background: #d2d2d2;
  }

  span:last-child {
    width: 35px;
  }

  &:not(:last-of-type) {
    margin-right: 15px;
  }

  &.active {
    border: 1px solid $mainBlue;

    span:first-child {
      color: #ffffff;
      background: $mainBlue;
    }
  }

  .check_icon {
    font-size: 26px;
    font-weight: bold;
  }
}

.exp_wrap {
  display: flex;
  margin-top: 18px;
  margin-bottom: 18px;

  .item {
    display: flex;
    width: 33%;
    align-items: center;
    flex-direction: column;

    .el-image {
      border: 1px solid #eeeeee;
    }

    span {
      margin-top: 10px;

      i {
        font-size: 20px;
        vertical-align: middle;
        margin-right: 3px;
      }
    }
  }
}

.fix-footer-btns {
  .el-divider {
    background-color: #eeeeee;
    width: 95%;
    margin: 15px auto;
  }
}
</style>
